import 'dart:async';
import 'dart:io';
// import 'package:amap_flutter_base/amap_flutter_base.dart';
// import 'package:amap_flutter_location/amap_flutter_location.dart';
// import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slider_drawer/flutter_slider_drawer.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/comcon_api.dart';
import 'package:lcapp/api/interface/login_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/address_info.dart';
import 'package:lcapp/basic/local_info.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/login/login_util.dart';
import 'package:lcapp/model/pay/in_app_pay.dart';
import 'package:lcapp/model/popover/popover.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/model/update/app_upgrade.dart';
import 'package:lcapp/page/indexpage.dart';
import 'package:lcapp/page/info_dialog/edit_info_dialog.dart';
import 'package:lcapp/page/slider_menu.dart';
import 'package:lcapp/routes/route.dart';
// import 'package:umeng_push_sdk/umeng_push_sdk.dart';
//
// import 'package:umeng_common_sdk/umeng_common_sdk.dart';
// import 'package:umeng_verify_sdk/umeng_verify_sdk.dart';

class DrawerPage extends StatefulWidget {
  const DrawerPage({Key? key}) : super(key: key);

  @override
  _DrawerPageState createState() => _DrawerPageState();
}
final GlobalKey<SliderDrawerState> sliderDrawerKey =
GlobalKey<SliderDrawerState>();
class _DrawerPageState extends State<DrawerPage> with WidgetsBindingObserver {
  // static const AMapPrivacyStatement amapPrivacyStatement =
  // AMapPrivacyStatement(hasContains: true, hasShow: true, hasAgree: true);

  late StreamSubscription subscription;
  late StreamSubscription loginSub;
  bool isOpen = false;
  bool isBack = false; //是否退出标识

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // AMapFlutterLocation.updatePrivacyShow(true, true);
    // AMapFlutterLocation.updatePrivacyAgree(true);
    // AMapFlutterLocation.setApiKey(
    //   "651c4f06a025de31b5b5ce448639f8b4",
    //   "f5a80374931dfb6b2997121da1de9d92",
    // );
    // const AMapWidget(
    //   ///必须正确设置的合规隐私声明，否则SDK不会工作，会造成地图白屏等问题。
    //   privacyStatement: amapPrivacyStatement,
    // );
    setUmengConfig();
    subscription = eventBus.on<HomeSliderChangeIndex>().listen((event) {
      setState(() {
        isOpen = event.isOpen!;
        print('slider状态====' + sliderDrawerKey.currentState!.isDrawerOpen.toString());
      });
    });
    loginSub = eventBus.on<LoginState>().listen((event) {
      if(AsrLocalInfo.userId!=null){
        LoginAPI.loginOnState();
        refreshUserInfo(refreshBlock: (){
          if(AppUpgrade.isUpdate==false){
            if(userInfo.profiles==null||userInfo.name==null||userInfo.address==null||userInfo.profiles!.isEmpty||userInfo.name!.isEmpty){
              SmartDialog.show(
                  alignment: Alignment.center,
                  clickMaskDismiss: false,
                  maskColor: Color.fromRGBO(0, 0, 0, 0.75), builder: (BuildContext context) {
                    return EditInfoDialog();
              },
              );
            }else{
              PopoverManager.getPops();
            }
          }
        });
      }else{
        print('AsrLocalInfo.token');
      }
    });
    AddressInfo.getAddress();
    AddressInfo.getPlList();
    if(AsrLocalInfo.userId!=null){
      LoginAPI.loginOnState();
      refreshUserInfo(refreshBlock: (){
        if(AppUpgrade.isUpdate==false){
          if(userInfo.profiles==null||userInfo.name==null||userInfo.address==null||userInfo.profiles!.isEmpty||userInfo.name!.isEmpty){
            SmartDialog.show(
              alignment: Alignment.center,
              clickMaskDismiss: false,
              maskColor: Color.fromRGBO(0, 0, 0, 0.75), builder: (BuildContext context) {
              return EditInfoDialog();
            },
            );
          }else{
            PopoverManager.getPops();
          }
        }
      });
    }else{
      print('AsrLocalInfo.token');
    }
    AppUpgrade.check();
    InAppPay.initApplePay(); //iOS内购初始化
  }

  void setUmengConfig()async{

    //推送
    // UmengPushSdk.setLogEnable(true);
    // UmengPushSdk.setPushEnable(true);
    // UmengPushSdk.register('641037b850e3320c3e64f462', 'APPStore');
    // int clientType;
    // if(Platform.isAndroid){
    //   clientType =1;
    // }else if(Platform.isIOS){
    //   clientType =2;
    // }
    // UmengPushSdk.setTokenCallback((result) {
    //   if(AsrLocalInfo.userId!=null&&clientType==1){
    //     CommonAPI.regDeviceToken(result, clientType, AsrLocalInfo.userId);
    //   }
    //   print('getRegisteredIdresult============' + result);
    // });
    // UmengPushSdk.getRegisteredId().then((value) {
    //   print('getRegisteredId============' + value+"------");
    //   if(AsrLocalInfo.userId!=null&&clientType==2){
    //     CommonAPI.regDeviceToken(value, clientType, AsrLocalInfo.userId);
    //   }
    // });
    //
    // UmengCommonSdk.platformVersion.then((value) => {
    //   print('UmengCommonSdk version== '+value)
    // });




    // UmengVerifySdk.register_android();
    // //一键登录
    // UmengCommonSdk.setPageCollectionModeManual();
    // UmengCommonSdk.initCommon('6410346c9a9ea961c470d676', '641037b850e3320c3e64f462', 'Umeng');
    // UmengVerifySdk.setVerifySDKInfo("8LnhC+clRB5gBiPb2SSkkaJekwyOWM0b6RjqtodGs/UsywyxwHVJGvDlfTUpXFvABxhU1WIfbW3WOy6xgmHslDrRnyK4gfzmbx1iML/xeImyjgq2dmXVkEPs/YHUV7YudlT2LphXiA7JQBwgWlIGNFI4w1uJV3/1ilA04793s84q4K3L4esNwcTgV3YslHQdZmAeVqpIrX3vgqHV6h/btRwuuxaORNMNWH9/TRiB/uu08uFVtaA2f64kMABUrEIMUwD5PzOgWwXa/Z6OcpSVUx4VyauJ7tiN2W0JMZI/IxDm9r+7u5I86Q==", "TVbVmXnYky40OZ2NXK5S4pDJ5F0KUBtTgVq8tGe+5iJ2frSdzJFE6W4Er0xfcKpAQb3rQdTWxdQf+Xbyx5S4sXUS1Yp1j4wmtYoY+rZLP6KFtL8qDo84mJwJ4bTc60K8VB7tLXNa4cs9wdD2HrJXe7YHqXaf9I/vNkwqMIJv/kotZf8sICNKEslMRDu8/3ChPAZ+uekg/ECZWUFU0HEWGbvpzx21lZihoeh5hA2Ks3dVHy+GlwmWoteGdY8Mu0QWoRlbW565Ehc=").then((value){
    //   print('setVerifySDKInfo===' + value.toString());
    // });
    // UmengVerifySdk.VerifyVersion.then((value) => {
    //   print('UmengVerifySdk version== '+value)
    // });
    //
    // if(Platform.isIOS){
    //    Map res = await UmengVerifySdk.checkEnvAvailableWithAuthType_ios('TVbVmXnYky40OZ2NXK5S4pDJ5F0KUBtTgVq8tGe+5iJ2frSdzJFE6W4Er0xfcKpAQb3rQdTWxdQf+Xbyx5S4sXUS1Yp1j4wmtYoY+rZLP6KFtL8qDo84mJwJ4bTc60K8VB7tLXNa4cs9wdD2HrJXe7YHqXaf9I/vNkwqMIJv/kotZf8sICNKEslMRDu8/3ChPAZ+uekg/ECZWUFU0HEWGbvpzx21lZihoeh5hA2Ks3dVHy+GlwmWoteGdY8Mu0QWoRlbW565Ehc=');
    //    if(res['resultCode'] == '600000'){
    //      LoginUtil.canLogin = true;
    //    }
    //    // showToast(res.toString());
    // }else{
    //  UmengVerifySdk.checkEnvAvailable_android(UMEnvCheckType.type_login);
    // }
    // UmengVerifySdk.accelerateLoginPageWithTimeout(5);
    //
    // UmengVerifySdk.getLoginTokenCallback((result) async{
    //   print('getLoginTokenCallback===' + result.toString());
    //   // showToast(result.toString());
    //   if(result['resultCode'] == '700001'){ //切换其他登录方式
    //     UmengVerifySdk.cancelLoginVCAnimated(true);
    //     Navigator.of(ASRRoute.navigatorKey.currentContext).pushNamed("LoginPage");
    //   }else if(result['resultCode'] == '600000'){
    //     UmengVerifySdk.cancelLoginVCAnimated(true);
    //     showLoading();
    //     ResponseData res = await LoginAPI.yysLogin(result['token']);
    //     hideLoading();
    //     if(res.code==200&&res.data!=null){
    //       showToast('登录成功');
    //       AsrLocalInfo.setToken(res.data['user']['token']);
    //       AsrLocalInfo.setUserId(res.data['user']['id']);
    //       await refreshUserInfo();
    //       if(userInfo.userstate == 0){
    //         Navigator.of(ASRRoute.navigatorKey.currentContext).pushNamed("ReginPage");
    //       }
    //     }
    //   }else if(result['resultCode'] == '600002'){
    //     UmengVerifySdk.cancelLoginVCAnimated(true);
    //     Navigator.of(ASRRoute.navigatorKey.currentContext).pushNamed("LoginPage");
    //     print('拉起失败');
    //   }
    // });
    // UmengVerifySdk.setTokenResultCallback_android((result) async{
    //   print('setTokenResultCallback_android===' + result.toString());
    //   // showToast(result.toString());
    //   if(result['code']=='600024'){
    //     LoginUtil.canLogin = true;
    //   }
    //   if(result['code'] == '700001'){ //切换其他登录方式
    //     UmengVerifySdk.cancelLoginVCAnimated(true);
    //     UmengVerifySdk.quitLoginPage_android();
    //     Navigator.of(ASRRoute.navigatorKey.currentContext).pushNamed("LoginPage");
    //   }else if(result['code'] == '600000'&&result['token']!=null){
    //     UmengVerifySdk.cancelLoginVCAnimated(true);
    //     UmengVerifySdk.quitLoginPage_android();
    //     ResponseData res = await LoginAPI.yysLogin(result['token']);
    //     if(res.code==200&&res.data!=null){
    //       showToast('登录成功');
    //       AsrLocalInfo.setToken(res.data['user']['token']);
    //       AsrLocalInfo.setUserId(res.data['user']['id']);
    //       await refreshUserInfo();
    //       if(userInfo.userstate == 0){
    //         Navigator.of(ASRRoute.navigatorKey.currentContext).pushNamed("ReginPage");
    //       }
    //     }
    //   }else if(result['code'] == '600002'||result['code'] == '600004'||result['code'] == '600005'){
    //     UmengVerifySdk.cancelLoginVCAnimated(true);
    //     UmengVerifySdk.quitLoginPage_android();
    //     Navigator.of(ASRRoute.navigatorKey.currentContext).pushNamed("LoginPage");
    //     print('拉起失败');
    //   }
    // });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      AppUpgrade.check();
      if(AsrLocalInfo.userId!=null){
        LoginAPI.loginOnState();
        refreshUserInfo(refreshBlock: (){
          setState(() {
          });
        });
      }
    }else if (state == AppLifecycleState.paused||state == AppLifecycleState.detached) {
      if(AsrLocalInfo.userId!=null){
        LoginAPI.loginOutState();
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    subscription.cancel();
    loginSub.cancel();
    if(AsrLocalInfo.token!=null){
      LoginAPI.loginOutState();
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        print('返回了======');
        SmartDialog.dismiss();
        if (isBack) {
          exit(0);
        } else {
          isBack = true;
          Future.delayed(Duration(milliseconds: 1500), () {
            isBack = false;
          });
        }
        return false;
      },
      child: Scaffold(
        body: SliderDrawer(
          key: sliderDrawerKey,
          isDraggable: false,
          appBar: Container(),
          slideDirection:SlideDirection.leftToRight,
          slider: SliderMenu(),
          child: Container(
            child: Stack(
              children: [
                IndexPage(),
                Positioned(child: Visibility(
                  child: GestureDetector(
                    onTap: (){
                      sliderDrawerKey.currentState?.closeSlider();
                      setState(() {
                        isOpen = false;
                      });
                    },
                    child: Container(
                      color: Color(0x2f000000),
                    ),
                  ),
                  visible: isOpen,
                ),left: 0,right: 0,top: 0,bottom: 0,)
              ],
            ),
          ),
        ),
      ),
    );
  }
}
